package com.css.fxfzxczh.modules.synthesizeInfoManage.personnelManagement.service.impl;


import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.druid.util.StringUtils;
import com.css.fxfzxczh.base.dict.service.DictService;
import com.css.fxfzxczh.constants.YNEnum;
import com.css.fxfzxczh.modules.synthesizeInfoManage.personnelManagement.entity.PersonnelManagement;
import com.css.fxfzxczh.modules.synthesizeInfoManage.personnelManagement.entity.Role;
import com.css.fxfzxczh.modules.synthesizeInfoManage.personnelManagement.repository.PersonnelManagementRepository;
import com.css.fxfzxczh.modules.synthesizeInfoManage.personnelManagement.service.PersonnelManagementService;
import com.css.fxfzxczh.modules.synthesizeInfoManage.personnelManagement.verify.ExcelVerifyHandler;
import com.css.fxfzxczh.modules.synthesizeInfoManage.personnelManagement.vo.ImportExcelVo;
import com.css.fxfzxczh.modules.synthesizeInfoManage.personnelManagement.vo.SysUserImportVo;
import com.css.fxfzxczh.util.CreateGson;
import com.css.fxfzxczh.util.PlatformDateUtils;
import com.css.fxfzxczh.util.PlatformObjectUtils;
import com.css.fxfzxczh.web.PlatformSessionContext;
import com.css.fxfzxczh.zcpt.sys.entity.SUser;
import com.css.fxfzxczh.zcpt.sys.entity.UserRegister;
import com.css.fxfzxczh.zcpt.sys.service.SUserService;
import com.css.fxfzxczh.zcpt.sys.service.SysAreaService;
import com.css.fxfzxczh.zcpt.sys.service.SysRoleService;
import com.css.util.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @Author: zhangSongRui
 * @CreateTime: 2023/01/10
 * @Description: 现场人员管理
 */
@Service
public class PersonnelManagementServiceImpl implements PersonnelManagementService {
    @Resource
    private PersonnelManagementRepository personnelManagementRepository;

    @Resource
    SUserService sUserService;

    @Resource
    DictService dictService;

    @Resource
    private SysAreaService sysAreaService;

    @Autowired
    ExcelVerifyHandler excelVerifyHandler;


    /**
     * 新增单条数据
     *
     * @param param
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(PersonnelManagement param) {
        PersonnelManagement personnelManagement = personnelManagementRepository.findByXsemIdAndTel(param.getTel(), param.getXsemId());
        if (!PlatformObjectUtils.isEmpty(personnelManagement)) {
            throw new RuntimeException("手机号 "+param.getTel()+"重复！");
        }
        param.setXpimId(UUID.randomUUID().toString().replaceAll("-", ""));
        param.setDelFlag(YNEnum.N.toString());
        String userID = PlatformSessionContext.getUserID(); // 获取当前登录用户
        param.setCreateUser(userID);
        param.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        //注册
        String userId = register(param);
        param.setUuid(userId);
        personnelManagementRepository.save(param);
        String role = param.getRole();
        String[] split = role.split(",");
        for(String item:split){
            //绑定角色
            sysAreaService.getSRoleUser(item, userId);
        }
    }

    /**
     * 修改单条数据
     *
     * @param param
     */
    @Override
    public void updateById(PersonnelManagement param) {
        String userID = PlatformSessionContext.getUserID(); // 获取当前登录用户
        param.setUpdateUser(userID);
        param.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        //新增角色
        PersonnelManagement byId = personnelManagementRepository.findById(param.getXpimId());
        String exp = "(^[, ]+)|([, ]+$)";
        String s = byId.getRole().replaceAll(exp, "");
        String[] old = s.split(",");
        String s1 = param.getRole().replaceAll(exp, "");
        String[] ne = s1.split(",");
        addRole(old, ne, param.getUuid());
        personnelManagementRepository.updateById(param);
        //删除对应角色
        if (!StringUtils.isEmpty(param.getRoleDeletion())) {
            //删除对应角色
            sysAreaService.deleteRole(param.getRole(), param.getUuid());
        }
    }

    @Override
    public void deleteById(List<String> ids) {
        personnelManagementRepository.deleteById(ids);
    }

    //将之前不曾有的角色新增
    private void addRole(String[] old, String[] ne, String userId) {
        Map<String, Integer> map = new HashMap<>();
        for (int i = 0; i < ne.length; i++) {
            map.put(ne[i], 1);
        }
        for (int i = 0; i < old.length; i++) {
            if (map.containsKey(old[i])) {
                int count = map.get(old[i]);
                count++;
                map.put(old[i], count);
            }
        }
        Iterator iter = map.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry<String, Integer> entry = (Map.Entry<String, Integer>) iter.next();
            if (entry.getValue() == 1) {
                sysAreaService.getSRoleUser(entry.getKey(), userId);
            }
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importExcel(MultipartFile file, String xsemId) throws Exception {
        // 导入的参数信息
        ImportParams params = new ImportParams();
        params.setTitleRows(1);
        params.setImportFields(new String[]{"省","市","县","姓名","性别","类别","角色","单位名称","手机号","描述信息"});
        params.setNeedVerify(true);
        params.setVerifyHandler(excelVerifyHandler);//校验
        InputStream inputStream = null;

            inputStream = file.getInputStream();
            ExcelImportResult<ImportExcelVo> result = ExcelImportUtil.importExcelMore(inputStream, ImportExcelVo.class, params);
            List<ImportExcelVo> failList = result.getFailList();
            if (PlatformObjectUtils.isNotEmpty(failList)) {
                StringBuilder errorMsg = new StringBuilder("<font size='5px' color='red'>导入失败：</font>");
                for (ImportExcelVo importExcelVo : failList) {
                    errorMsg.append("<font size='4px' ><br>").append("第").append(importExcelVo.getRowNum() + 1).append("行： ").append(importExcelVo.getErrorMsg()).append("</font>");
                }
                throw new RuntimeException(errorMsg.toString());
            }
            List<PersonnelManagement>  list= getList(result.getList(),xsemId);
            Map<String, String> roleMap = getRoleMap();
            //将所有未注册的手机号注册
            for (PersonnelManagement personnelManagement : list) {
                String userId = register(personnelManagement);
                String[] split = personnelManagement.getRole().split("、");
                StringBuilder roleIds=new StringBuilder();
                for(String item:split){
                    if (roleMap.get(item) != null) {
                        String rid = roleMap.get(item);
                        roleIds.append(rid+",");
                        sysAreaService.getSRoleUser(rid, userId);
                    }
                }
                personnelManagement.setRole(roleIds.substring(0, roleIds.length() - 1));
                personnelManagement.setUuid(userId);
            }
            //批量入库
            personnelManagementRepository.batchSave(list);


    }

    private List<PersonnelManagement> getList(List<ImportExcelVo> data, String xsemId) throws UnsupportedEncodingException {
        ArrayList<PersonnelManagement> personnelManagements = new ArrayList<>();
        String userID = PlatformSessionContext.getUserID();
        String user = sUserService.getSUser(userID);
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        for (int i = 0; i < data.size(); i++) {
            ImportExcelVo importExcelVo = data.get(i);
            PersonnelManagement obj = new PersonnelManagement();
            //id
            obj.setXpimId(UUID.randomUUID().toString().replaceAll("-", ""));
            obj.setDelFlag(YNEnum.N.toString());
            obj.setCreateUser(userID);
            obj.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
            obj.setCompany(sUser.getOrgName());
            //地震事件编号
            obj.setXsemId(xsemId);
            //暂停一下,避免被认定为攻击
            try {
                TimeUnit.MILLISECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            String divisionId = getDivisionId(importExcelVo.getProvince(),
                    importExcelVo.getCity() == null ? "" : importExcelVo.getCity() ,
                    importExcelVo.getCounty() == null ? "" : importExcelVo.getCounty());
            String[] s = divisionId.split("_");
            if(!PlatformObjectUtils.isEmpty(importExcelVo.getProvince())){
                obj.setProvinceId(s[0]);
            }
            if(!PlatformObjectUtils.isEmpty(importExcelVo.getCity())){
                obj.setCityId(s[1]);
            }
            if(!PlatformObjectUtils.isEmpty(importExcelVo.getCounty())){
                obj.setCountyId(s[2]);
            }

            // 根据省市县名称获得省市县id _ 分割
            /*String divisionIds = sysAreaService.getIdByCondition(
                    URLEncoder.encode(importExcelVo.getProvince(), "UTF-8"),
                    URLEncoder.encode(importExcelVo.getCity(), "UTF-8"),
                    URLEncoder.encode(importExcelVo.getCounty(), "UTF-8"));


            obj.setProvinceId(s[0]);
            //市id  根据市名称获得省id 注册用
            obj.setCityId(s[1]);
            //县id  根据县名称获得省id 注册用
            obj.setCountyId(s[2]);*/
            //人员姓名
            obj.setPersonName(importExcelVo.getPersonName());
            //性别
            obj.setGender(importExcelVo.getSex());
            //现场人员类别
            obj.setCategory(dictService.getKeyByDictCodeAndValue("rylb", importExcelVo.getCategory()));//从数据字典中获取key);
            obj.setRole( importExcelVo.getRole());
            //现场人员单位
            obj.setUnit(importExcelVo.getUnit());
            //电话号码
            obj.setTel(importExcelVo.getTel());
            //描述信息
            obj.setCommentInfo(importExcelVo.getCommentInfo());
            personnelManagements.add(obj);
        }
        return personnelManagements;
    }

    private String getDivisionId(String province,String city,String area) throws UnsupportedEncodingException {
        return sysAreaService.getIdByCondition(URLEncoder.encode(province, "utf-8"), URLEncoder.encode(city, "utf-8"), URLEncoder.encode(area, "utf-8"));
    }
    /**
     * 分页查询
     *
     * @param queParams
     * @param curPage
     * @param pageSize
     * @return
     */
    @Override
    public Map<String, Object> getPage(PersonnelManagement queParams, int curPage, int pageSize) {
        Map<String, Object> page = personnelManagementRepository.getPage(queParams, curPage, pageSize);
        return page;
    }

    //手机号对比与注册
    private String register(PersonnelManagement personnelManagement) {
        UserRegister userRegister = new UserRegister();
        try {
            //密码
            userRegister.setPassword(Md5Util.getMD5("admin111111"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        //手机号
        userRegister.setMobile(personnelManagement.getTel());
        //真实姓名
        userRegister.setRealName(personnelManagement.getPersonName());
        //省id
        userRegister.setProvinceId(personnelManagement.getProvinceId());
        //市id
        userRegister.setCityId(personnelManagement.getCityId());
        //县id
        userRegister.setCountyId(personnelManagement.getCountyId());
        return sysAreaService.registerNewUser(userRegister);
    }

    private Map<String, String> getRoleMap() {
        //获取角色信息
        List<Map> maps = sysAreaService.getRole();
        //取出固定角色id
        Map<String, String> getRoleId = new HashMap<>();
        for (Map map : maps) {
            getRoleId.put(String.valueOf(map.get("roleName")), String.valueOf(map.get("roleId")));
        }
        return getRoleId;
    }

    //获取单位,创建人,创建时间
    public PersonnelManagement getHeadInfo() {
        PersonnelManagement personnelManagement = new PersonnelManagement();
        String userId = PlatformSessionContext.getUserID();
        String user = sUserService.getSUser(userId);
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        personnelManagement.setCreateUser(sUser.getUserName());
        personnelManagement.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        personnelManagement.setCompany(sUser.getOrgName());
        return personnelManagement;
    }

    @Override
    public PersonnelManagement findById(String id) {
        PersonnelManagement byId = personnelManagementRepository.findById(id);
        String user = sUserService.getSUser(byId.getCreateUser());
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        byId.setUserName(sUser.getUserName());
        return byId;
    }

    //获取角色
    @Override
    public List<Role> getRole() {
        //获取角色信息
        List<Map> maps = sysAreaService.getRole();
        ArrayList<Role> list = new ArrayList<>();
        for (Map map : maps) {
            Role role = new Role();
            //角色id
            role.setRoleId(String.valueOf(map.get("roleId")));
            //角色名称
            role.setRole(String.valueOf(map.get("roleName")));
            list.add(role);
        }
        //获取所有角色
        return list;
    }

    @Override
    public PersonnelManagement findByXsemIdAndTel(String tel, String xsemId) {
        return personnelManagementRepository.findByXsemIdAndTel(tel,xsemId);
    }

    @Override
    public void sysUserImport(SysUserImportVo sysUserImportVo) {
        String userId = PlatformSessionContext.getUserID();
        String createUser = sUserService.getSUser(userId);
        SUser sUser = CreateGson.createGson().fromJson(createUser, SUser.class);

        List<PersonnelManagement> personnelList = sysUserImportVo.getUserList();
        String xsemId = sysUserImportVo.getXsemId();
        for(PersonnelManagement personnel:personnelList){
            PersonnelManagement personnelManagement = personnelManagementRepository.findByXsemIdAndTel(personnel.getTel(), xsemId);
            if (!PlatformObjectUtils.isEmpty(personnelManagement)) {
                throw new RuntimeException("手机号 "+personnel.getTel()+"重复！");
            }
            personnel.setXpimId(UUID.randomUUID().toString().replaceAll("-", ""));
            personnel.setXsemId(xsemId);
            personnel.setDelFlag(YNEnum.N.toString());
            personnel.setCreateUser(userId);
            personnel.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
            personnel.setCompany(sUser.getOrgName());
            personnelManagementRepository.save(personnel);
        }

    }
}
